<template>
	<div class="echarts-box">
		<div ref="demoRefs" class="echarts-main"></div>
	</div>
</template>

<script setup>
import { ref, onMounted, nextTick, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';

const demoRefs = ref(null);
let demoChart = null;
const getData = () => {
	// 获取接口数据后开始渲染echarts
	echartsDraw();
};
onMounted(() => {
	getData();
});
const echartsDraw = (datas) => {
	datas = [1, 2, 3];
	demoChart = echarts.init(
		demoRefs.value,
		{},
		{
			renderer: 'svg'
		}
	);
	window.addEventListener('resize', () => {
		if (demoChart) {
			demoChart.resize();
		}
	});
	let optionWithData = {
		grid: {
			top: '10%',
			left: '0%',
			right: '0%',
			bottom: '0%',
			containLabel: true
		},
		legend: {
			data: ['保养', '巡检', '维修'],
			icon: 'circle',
			right: 0
		},
		tooltip: {
			show: true,
			trigger: 'axis',
			formatter: function (params) {
				let tooltipStr = '';
				params.reverse(); // 反转参数数组
				for (let i = 0; i < params.length; i++) {
					tooltipStr += params[i].marker + ' ' + params[i].seriesName + '： ' + params[i].value + '<br>';
				}
				return params[0].name + '<br>' + tooltipStr;
			}
		},
		xAxis: {
			type: 'category',
			data: ['2023-09-01', '2023-09-03', '2023-09-06', '2023-09-09', '2023-09-11']
		},
		yAxis: {
			type: 'value'
		},
		series: [
			{
				name: '维修',
				type: 'bar',
				stack: '总量',
				data: [25, 10, 40, 30, 20], // 调整数据顺序
				barMaxWidth: 30
			},
			{
				name: '巡检',
				type: 'bar',
				stack: '总量',
				data: [30, 20, 35, 25, 15], // 调整数据顺序
				barMaxWidth: 30
			},
			{
				name: '保养',
				type: 'bar',
				stack: '总量',
				data: [25, 15, 30, 20, 10], // 调整数据顺序
				barMaxWidth: 30
			}
		]
	};
	let optionWithoutData = {
		grid: {
			top: '0%',
			left: '0%',
			right: '0%',
			bottom: '0%',
			containLabel: true
		},
		graphic: {
			elements: [
				{
					type: 'text',
					left: 'center',
					top: 'middle',
					style: {
						text: '暂无数据',
						fill: '#999',
						fontSize: 14
					}
				}
			]
		}
	};
	let option = datas.length > 0 ? optionWithData : optionWithoutData;
	option && demoChart.setOption(option);
};

// 离开页面后请销毁echarts
onBeforeUnmount(() => {
	demoChart = null;
	echarts.dispose(demoRefs.value);
});
</script>

<style lang="scss">
.echarts-box {
	.echarts-main {
		width: 100%;
		min-width: 500px;
		height: 300px;
	}
}
</style>
